<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

use app\index\model\UserLog;

use service\JsonService;
use service\UtilService;
use service\RequestService;

function isHttps()
{
    if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
        return true;
    } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return true;
    }
    return false;
}

function traverseTree($tree, $callback)
{
    foreach ($tree as $node) {
        $children = isset($node['_child']) ? $node['_child'] : [];
        // 调用回调函数处理当前节点
        call_user_func($callback, $node);
        // 递归遍历子节点
        if (!empty($children)) {
            traverseTree($children, $callback);
        }
    }
}

/**
 * [ tp自带写入日志 -详细]
 * @param array,string  $log_content [内容]
 * @param string 　　　　$keyp        [文件名]
 * @return [type]         　　　　　　[description]
 */
function tp_log($log_content, $keyp)
{
    \think\Log::init(['type' => 'File', 'path' => ROOT_PATH . 'logs' . DS . $keyp . DS]);
    \think\Log::write($log_content);
}

function tree_to_list($tree, $children = 'children', &$list = array())
{
    if (is_array($tree)) {
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if (isset($reffer[$children]) && !empty($reffer[$children])) {
                //unset($reffer[$children]);
                tree_to_list($value[$children], $children, $list);
            }
            $list[] = $reffer;
        }
    }
    return $list;
}

function treeToArray($tree, &$result = array())
{
    if (!empty($tree)) {
        foreach ($tree as $node) {
            $result[] = $node;
            if (!empty($node['_child'])) {
                treeToArray($node['_child'], $result);
            }
        }
    }
    return $result;
}

function generateTree($flatArray, $parentId = 0)
{
    $tree = [];
    foreach ($flatArray as $item) {
        if ($item['pid'] === $parentId) {
            $node = $item;
            $node['children'] = generateTree($flatArray, $item['id']);
            $tree[] = $node;
        }
    }
    return $tree;
}

function getLeafNodes($tree)
{
    $leafNodes = [];
    foreach ($tree as $node) {
        if (!isset($node['_child']) || empty($node['_child'])) {
            $leafNodes[] = $node;
        } else {
            $leafNodes = array_merge($leafNodes, getLeafNodes($node['_child']));
        }
    }
    return $leafNodes;
}


function getdepartmentidsv1()
{
    return [
        "50048834",//"od-8ddfc12cb88fe570b976783061e3b82d",//董事会办公室（党群办公室、总裁办公室）
        "50034333",//"od-2815231f5df8d594d088d3f70ad12928",//本体建设中心
        "10002140",//"od-ffa351e0c2d872193fc884348609bce8",//发展投资中心
        "10002141",//"od-6a50e056fb32676a84b826fbb8147b4b",//营销服务中心
        "50038641",//"od-e36f6dee330e94fb817722e4247bbdd7",//客研中心
        "10002145",//"od-107361cd13b7cca34ad0357e8eecb10c",//工程管理中心
        "10002153",//"od-29df1d1113b0f56c3258f8e3ef36866e",//成本招采中心
        "50042357",//"od-8472c9573b27074100a54323ca94be61",//研发设计中心
        "10002154",//"od-5f0d52c3eb54b56ac68082699a2d0d8e",//运营管理中心
        "50067850",//"od-4c94ed3b5d138c32eb95eee3465342e1",//研究院
        "10000009",//"od-8f95c001be01e30bf90cf90a27e3cd68",//财务资金中心
        "50048839",//"od-49edcab620cbe730906bbfdbe7f75359",//产融事业部（综合产业办公室）
        "50048840",//"od-8d16a1ef3a9e2ba7493115916b35699f",//商管事业部
        "50047249",//"od-50f4f327df146017cd9f0f6261123453",//业务委员会
        "50048746",//"od-41f45c5f1262dc7884269c97bdd1c3fb",//绿城大学
        "10000001",//"od-e4cb03e12346c704ed2aad54b48542c5",//董事会
        "10000002",//"od-7c3752fc0ef0b2c60b679eae05332683",//经营班子
        "50025989",//"od-dcc37f59496d8273dfa0c71576274226",//辅助类人员
    ];
}

function getdepartmentids()
{
    return [
        "10000000",//绿城中国控股有限公司
        "94001249",//其他-外协单位-数字化建设中心服务团队
    ];
}

function specialdepartmentids()
{
    return [
        "99990176",//其他
        "99900001",//外协单位
    ];
}

function removeNonChineseCharacters($str) {
    return preg_replace('/[^\x{4e00}-\x{9fa5}]/u', '', $str);
}

//解析url去除\u002
function decodeUnicode($str)
{
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function ($matches) {
        return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");
    }, $str);
}

/*
* Base64生成图片文件,自动解析格式
*/
function createBase64($base64, $path, $filename)
{

    $resinfo = array();
    //匹配base64字符串格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)) {
        //保存最终的图片格式
        $postfix = $result[2];
        $base64 = base64_decode(substr(strstr($base64, ','), 1));
        $filename = $filename . '.' . $postfix;
        $path = $path . $filename;
        //创建图片
        if (file_put_contents($path, $base64)) {
            $resinfo['state'] = 1;
            $resinfo['filename'] = $filename;
        } else {
            $resinfo['state'] = 2;
            $resinfo['err'] = 'Create img failed!';
        }
    } else {
        $resinfo['state'] = 2;
        $resinfo['err'] = 'Not base64 char!';
    }

    return $resinfo;
}

/**
 * 图片转base64格式
 *
 */
function base64EncodeImage($image_file)
{
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}

/**
 * @param $arrs
 * @return bool|int
 * @name: AddLogs
 * @describe: 日志
 */
function addLogs($arrs)
{
    $log = new UserLog();
    try {
        //dump($arrs);exit;
        $resd = $log->allowField(true)->save($arrs);
        return $resd;
    } catch (\Exception $exception) {
        return JsonService::fail($exception->getMessage());
    }
}

/**
 * @param null $directory
 * @return bool
 * @name: clear_temp
 * @describe:刷新系统静态文件
 */
function clear_temp($directory = null)
{
    $directory = empty($directory) ? ROOT_PATH . 'runtime/temp/' : $directory;
    if (is_dir($directory) == false) {
        return false;
    }
    $handle = opendir($directory);
    while (($file = readdir($handle)) !== false) {
        if ($file != "." && $file != "..") {
            is_dir($directory . '/' . $file) ?
                clear_cache($directory . '/' . $file) :
                unlink($directory . '/' . $file);
        }
    }
    if (readdir($handle) == false) {
        closedir($handle);
        rmdir($directory);
    }
}

function sendmsg($phone, $content)
{
    $content = mb_convert_encoding($content, "UTF-8");
    $msg_url = "http://121.41.98.232:8001/sms/interface/sendmess.htm?username=GTG-YY&userpwd=jWLjIhQy2IER&mobiles={$phone}&content={$content}";
    $client = new \GuzzleHttp\Client();
    $res = $client->post($msg_url);
    $string = $res->getBody()->getContents();
    $xml = simplexml_load_string($string);
    $array = json_decode(json_encode($xml), true);
    return $array;
}

function randSole($type = 0, $length = 18, $time = 0)
{
    $str = $time == 0 ? '' : date('YmdHis');
    switch ($type) {
        case 1:
            $rand = 'qwertyuioplkjhgfdsazxcvbnm';
            break;
        case 2:
            $rand = 'QWERTYUIOPLKJHGFDSAZXCVBNM';
            break;
        case 3:
            $rand = '123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM';
            break;
        case 4:
            $rand = '!@#$%^&*()_+=-~`';
            break;
        case 5:
            $rand = '123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM!@#$%^&*()_+=-~`';
            break;
        case 6:
            $rand = 'qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM';
            break;
        default:
            $rand = '123456789';
            break;
    }

    for ($i = 0; $i <= $length; $i++) {
        if (mb_strlen($str) < $length) {
            $str .= $rand[mt_rand(0, strlen($rand) - 1)];
        }
    }
    return $str;
}

function isMobile($value)
{
    $rule = '^1(3|4|5|7|8|9)[0-9]\d{8}$^';
    $result = preg_match($rule, $value);
    if ($result) {
        return true;
    } else {
        return false;
    }
}

function getFiles($dir)
{
    $files = [];
    if (is_dir($dir)) { // 判断目录是否存在
        $handle = opendir($dir);
        while (($file = readdir($handle)) !== false) {
            if ($file != "." && $file != "..") {
                $path = $dir . "/" . $file;
                if (is_dir($path)) { // 如果是目录，递归调用
                    $files = array_merge($files, getFiles($path));
                } else { // 如果是文件，添加到结果数组中
                    if (is_file($path) && getExt($path) == 'php') {
                        $files[] = $path;
                    }
                }
            }
        }
        closedir($handle); // 关闭目录句柄
    }
    return $files;
}

function getExt($filename)
{
    $array = @explode('.', $filename);
    $ext = @end($array);
    return $ext;
}



